/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hoot.control.utilities.exportdataset Export control for ingested dataset.
//
//
// NOTE: Please add to this section with any modification/addtion/deletion to the behavior
// Modifications:
//      17 Feb. 2016
//      15 Apr. 2016 eslint updates -- Sisskind
//      31 May  2016 OSM API Database export type -- bwitham
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

Hoot.control.utilities.exportdataset = function(context) {
    var _events = d3.dispatch();
    var _instance = {};

    var _container;
    var _dataset;
    var _transCombo;

    var _overrideList = {};

    _instance.getOverrideList = function(){
        return _overrideList;
    };

    _instance.setOverrideList = function(tagList){
        _overrideList = tagList;
    };

    /**
    * @desc Entry point where it creates form.
    * @param dataset - Target dataset meta data.
    * @param translations - Translations meta data.
    **/
    _instance.exportDataContainer = function(dataset, translations) {
        _createDialog(dataset, translations);
    };

    /**
    * @desc Internal form creation.
    * @param dataset - Target dataset meta data.
    * @param translations - Translations meta data.
    **/
    var _createDialog = function(dataset, translations) {
        _dataset = dataset;
        var placeHolder = 'NSG Topographic Data Store (TDS) v6.1';//'Select Data Translation Schema'

        _transCombo = [];

        // filters for exportable translations
        _.each(translations, function(tr){
          if(tr.CANEXPORT && tr.CANEXPORT === true){
              _transCombo.push(tr);
          }
        });
        if(_transCombo.length === 1){
            var emptyObj = {};
            emptyObj.NAME='';
            emptyObj.DESCRIPTION='';
            _transCombo.push(emptyObj);
          }

        var exportFormatList =
          [{'DESCRIPTION': 'File Geodatabase'}, {'DESCRIPTION': 'Shapefile'},
           //{'DESCRIPTION': 'Web Feature Service (WFS)'},
           {'DESCRIPTION': 'OpenStreetMap (OSM)'},
           {'DESCRIPTION': 'OpenStreetMap (PBF)'}];
        if (_dataset.canExportToOsmApiDb === true)
        {
            exportFormatList.push({'DESCRIPTION': 'OSM API Database'});
        }

        var d_form = [{
            label: 'Translation Schema for Output File',
            id: 'fileExportTranslation',
            combobox: {'data':_transCombo, 'command': _populateTranslations },//transCombo,//exportResources,
            placeholder: { 'default': placeHolder, 'command': _getTranslationComboPlaceHolder},
            inputtype:'combobox'
        },  {
            label: 'Include Hoot Tags',
            type: 'exportHootTags',
            inputtype:'checkbox',
            checkbox:'cboxExportHootTags',
            hidden: true
        },  {
            label: 'Export Format',
            id: 'fileExportFileType',
            combobox: {'data': exportFormatList, 'command': _populateTranslations},
            placeholder: 'File Geodatabase',
            inputtype:'combobox'
        }, {
            label: 'Append to ESRI FGDB Template?',
            id: 'appendFGDBTemplate',
            inputtype:'checkbox',
            checkbox:'cboxAppendFGDBTemplate'
        }, {
            label: 'Output Name',
            id: 'fileExportOutputName',
            placeholder: dataset.name || 'Output Name',
            inputtype:'text',
            text: dataset.name || 'Output Name',
            onchange: _validateOutputName
        }, {
            label: 'Set tag overrides',
            id: 'exportTagOverrides',
            inputtype: 'link',
            link: 'linkTagOverrides',
            onclick: _overrideTagsHandler
        }];


        var d_btn = [
                        {
                            text: 'Export',
                            location: 'right',
                            id: 'exportDatasetBtnContainer',
                            onclick: _submitClickHandler
                        }
                    ];

        var meta = {};
        meta.title = (dataset.name || 'Export Dataset');
        meta.form = d_form;
        meta.button = d_btn;

        _instance.setOverrideList({});

        _container = context.hoot().ui.formfactory.create('body', meta);
    };

    var _overrideTagsHandler = function() {
        context.hoot().control.utilities.settagoverrides.setTagOverridesContainer();
    };

    /**
    * @desc Export request click handler,
    **/
    var _submitClickHandler = function() {
        if(!d3.selectAll('.invalidName').empty()){
            return;
        }

        var submitExp = d3.select('#exportDatasetBtnContainer');
        submitExp.insert('div',':first-child').classed('_icon _loading row1 col1 fr',true);
        context.hoot().model.export.exportData(_container, _dataset, function(status){


            if(status === 'failed'){
                iD.ui.Alert('Export has failed or partially failed.','warning',new Error().stack);
                _container.remove();
            } else {
                /*var tblContainer = d3.select('#wfsdatasettable');
                context.hoot().view.utilities.wfsdataset.populateWFSDatasets(tblContainer);*/
                _container.remove();
            }
        });
    };

    /**
    * @desc Output name validation helper function.
    **/
    var _validateOutputName = function() {
        //ensure output name is valid
        var resp = context.hoot().checkForUnallowedChar(this.value);
        if(resp !== true){
            d3.select(this).classed('invalidName',true).attr('title',resp);
        } else {
            d3.select(this).classed('invalidName',false).attr('title',null);
        }
    };

    /**
    * @desc Helper function to retrieve place holder text
    * @param field - fieldset metadata.
    **/
    var _getTranslationComboPlaceHolder = function(field) {
        var defTrans = _.find(field.combobox.data, {DESCRIPTION: field.placeholder.default});
        if(defTrans === undefined){
            return field.combobox.data[0].DESCRIPTION;
        } else {
            return defTrans.DESCRIPTION;
        }
    };

    /**
    * @desc Populate available translations.
    * @param a - Translations list combo meta data.
    **/
    var _populateTranslations = function(a) {
        var combo = d3.combobox()
            .data(_.map(a.combobox.data, function (n) {
                return {
                    value: n.DESCRIPTION,
                    title: n.DESCRIPTION
                };
            }));
        d3.select(this)
            .style('width', '100%')
            .call(combo);

        d3.select(this)
            .on('change',function(){
                _checkForOptions();
            });
    };

    /**
    * @desc Toggler for Append to ESRI FGDB Template checkbox.
    **/
    var _checkForOptions = function(){
        var hideFGDB=false;
        var hideExport=false;

        var exportType = d3.select('#fileExportFileType').value();
        var transType = d3.select('#fileExportTranslation').value();

        // Check if output type is File Geodatabase
        if (exportType===''){exportType=d3.select('#fileExportFileType').attr('placeholder');}
        if (transType===''){transType=d3.select('#fileExportTranslation').attr('placeholder');}

        //if (transType==='OpenStreetMap.org (OSM)'){d3.select('#fileExportFileType').value('OpenStreetMap (OSM)');}

        if(exportType!=='File Geodatabase'){
         hideFGDB=true;
        }

        var selTrans = _.find(_transCombo,{'DESCRIPTION':transType});
        if(selTrans){
         if(selTrans.NAME.substring(0,3)!=='TDS'){
             hideFGDB=true;
         }
         if(selTrans.NAME.substring(0,3)!=='OSM'){ 
            hideExport=true;
        }
        } else {
         hideFGDB=true;
         hideExport=true;
        }

        d3.select('.cboxAppendFGDBTemplate').classed('hidden',hideFGDB);
        if(hideFGDB){
         d3.select('.cboxAppendFGDBTemplate').select('input').property('checked',false);
        }

        d3.select('.cboxExportHootTags').classed('hidden',hideExport);
        if(hideExport){
            d3.select('.cboxExportHootTags').select('input').property('checked',false);
        }
    };




    return d3.rebind(_instance, _events, 'on');
};
